// 引入接口文件
import {
  areAddressGet,
} from './reportedClientDetailServ'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
/*isEmpty 对象是否为空
 *isArray 对象是否数组
 *cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge, pick } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'
import AppBus from '../../../utils/bus'
let productTypeLabelMap = { 1: '详细房号', 2: '车位位置', 3: '商铺位置', }
// 初始默认状态
const defultState = {
  xxx: '1',
  id: '',
  loading: false,
  btnLoading: false,
  pageType: 'detail',
  tableData: [],
  pageConfig: {},
  
  detailInfo: {
    mobile:'150****2568',
    mobile_arr:'150****2568'.split(''),
  },
  houseList: [],
  targetKeys: [],
  selectedKeys: [],
  
  formData: {
    switchFlag:false,
    mobile_arr:'150****2568'.split(''),

  },
  modalObj: {
    visible: false,
  }
}

// 声明module
const tmpModule = {
  // namespace: 'secondKillingSetting',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          console.log('subscriptions', pathname, query)
          if (query.pageType == 'edit') {
            dispatch({
              type: 'queryInfo',
              payload: {
                pageType: query.pageType,
                id: query.id,
              }
            })
          } else {
            dispatch({
              type: 'updateStore',
              payload: {
                pageType: query.pageType,
                id: query.id,
              }
            })
          }
          dispatch({ type: 'getArea', payload: {} })
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    // 查询记录  详情
    * queryInfo({ payload }, { put, call, select }) {
      let { id, detailInfo, formData, tags, imageUrls } = yield select(state => state[tmpModule.namespace])
      const { success, msg, data } = yield call(getDetail, { id: payload.id || id })
      if (success) {
        detailInfo = data || {}
        formData = data || {}
        formData.projectId = formData.productId;
        tags = data.tags || []
        imageUrls = data.imageUrls || []
        formData.productLabel = productTypeLabelMap[formData.productType] || null
        if(!formData.houseTypeName){
          formData.houseTypeName=['','','',''];//x室x厅x卫
        }else{
          formData.houseTypeName=(formData.houseTypeName||'').split(/[室|厅|厨|卫]/);//x室x厅x卫
          if(formData.houseTypeName>4){
            formData.houseTypeName.splice(2,1)//去掉厨房
          }
        }
        yield put ({type: `getHouseArea`, payload: {province: data.province, city:data.city,pageSize: 10000}})
        yield put ({type: `queryAccount`, payload: {id:formData.productId}})
        // const { success, rows } = yield call(houseListGet, { province: data.province, city: data.city, pageSize: 10000 });
        // if (success) {
        //   yield put({ type: 'updateStore', payload: { houseList: rows || [] } })
        // }
      }
      yield put({
        type: 'updateStore',
        payload: {
          detailInfo,
          formData,
          tags,
          imageUrls,
          ...payload,
        }
      })
    },

    // 修改
    * update({ payload }, { put, select, call }) {
      let { id, formData, tags, imageUrls } = yield select(state => state[tmpModule.namespace])
      let params = {
        seckillProductId: id,
        ...pick(formData, ['detail', 'area', 'productType', 'propertyType', 'seckillPrice',
          'originalPrice', 'initPrice', 'grads', 'securityMoney', 'earnestMoney', 'squarePrice', 'orientation',
          'imageUrls', 'tags', 'salePrice', 'consultantMobile', 'realtyConsultant', 'productLabel', 'projectId']),
        imageUrls,
      }
      // 商品类型非房源，不用传户型和户型朝向
      if(formData.productType==1){
        params.houseTypeName=formData.houseTypeName[0]+'室'+formData.houseTypeName[1]+'厅'+formData.houseTypeName[2]+'卫'
      }else{
        params.houseTypeName=''
        params.orientation=''
      }
      
      const { success, msg, data } = yield call(update, { ...params })
      if (success) {
        message.success('操作成功', 1, () => {
          // yield put({type: 'queryInfo', payload: {}})
          let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
          console.log('urlArray', urlArray)
          AppBus.emit('closeTab', {
            key: urlArray[0],
            cbf: () => {
              hashHistory.push(urlArray[1])
            }
          })
        })
      }
    },

    // 新增 projectId,houseTypeName,detail,area,,productType,propertyType,initPrice,grads,securityMoney,earnestMoney,squarePrice,orientation,imageUrls,tags
    * create({ payload }, { put, select, call }) {
      let { id, formData, tags, imageUrls, } = yield select(state => state[tmpModule.namespace])
      let params = {
        ...pick(formData, ['projectId', 'houseTypeName', 'detail', 'area', 'productType', 'propertyType', 'initPrice', 'grads', 'originalPrice', 'securityMoney', 'earnestMoney', 'squarePrice', 'orientation', 'imageUrls', 'tags', 'salePrice', 'consultantMobile', 'realtyConsultant']),
        imageUrls,
      }
      // 商品类型非房源，不用传户型和户型朝向
      if(formData.productType==1){
        params.houseTypeName=formData.houseTypeName[0]+'室'+formData.houseTypeName[1]+'厅'+formData.houseTypeName[2]+'卫'
      }else{
        params.houseTypeName=''
        params.orientation=''
      }
      
      const { success, msg, data } = yield call(create, { ...params })
      if (success) {
        message.success('操作成功', 1, () => {
          // yield put({type: 'queryInfo', payload: {}})
          let urlArray = MODULE_TO_ROUTES[tmpModule.namespace].urlArray
          console.log('urlArray', urlArray)
          AppBus.emit('closeTab', {
            key: urlArray[0],
            cbf: () => {
              hashHistory.push(urlArray[1])
            }
          })
        })
      }
    },

    // 获取区域地址
    * getArea({ payload }, { put, call, select }) {
      try {
        const { success, data } = yield call(areAddressGet)
        if (success) {
          //todo: 接口格式调整后删除
          let arr = [data[0]]
          data[0] = {
            label: '北京',
            value: '110100',
            children: arr
          }
          //去掉第三级，
          for (var i = 0; i < 33; i++) {
            for (var j = 0; j < data[i].children.length; j++) {
              delete data[i].children[j].children
            }
          }
          yield put({ type: 'updateStore', payload: { allAddress: data } })
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 获取户型项目
    *getHouseArea({ payload }, { put, call, select }) {
      try {
        const { success, rows } = yield call(houseListGet, { ...payload, pageSize: 10000 })
        if (success) {
          let list=rows||[]
          let arr=[]
          list.map((item,index)=>{
            arr.push({ label: item.name||'', value: item.productId+''||'' })
          })
          yield put({ type: 'updateStore', payload: { houseList: arr || [] } })
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 标签列表
    * getLabelQueryList({ payload }, { put, call, select }) {
      try {
        const { rows } = yield call(labelQueryList, {type:5})
        yield put({ type: 'updateStore', payload: { tagsList: rows } })
      } catch (e) {
        console.log(e)
      }
    },
    // 对公账户
    * queryAccount({ payload }, { put, call, select }) {
      let {id}=payload
      try {
        const { rows } = yield call(queryAccount, {id})
        yield put({ type: 'updateStore', payload: { accountList: rows } })
      } catch (e) {
        console.log(e)
      }
    },

    * gethouseTypeList({ payload }, { put, call, select }) {
      try {
        let params = {
          pageNo: 1,
          pageSize: 1000,
          ...payload
        }
        const { success, msg, rows } = yield call(gethouseTypeList, { ...params })
        let list = []
        yield put({ type: 'updateStore', payload: { houseTypeList: rows || [] } })

      } catch (e) {
      }
    },
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
